from ajson import aj

from db_base import UserOrm, MyFactory
from utils import Error
from . import user_v
from flask import request, Response


@user_v.route('/login/', methods=['POST'])
def login():
    data = aj.load(request.get_data(as_text=True))
    email = data.get('email')
    password = data.get('password')
    item = UserOrm.orm.find().where(email=email, password=password).end()
    if not item or len(item) == 0:
        return Error('账号或密码错误', 400)

    return Response(item.first().to_json(), status=200)


@user_v.route('/join/', methods=['POST'])
def join():
    data = aj.load(request.get_data(as_text=True))
    email = data['email']
    password = data['password']
    pwd = data['pwd']

    if len(password) <= 6:
        return Error('密码长度需要大于6位数')
    if password != pwd:
        return Error('两次输入密码不一致')
    item = UserOrm.orm.find().where(email=email).end()
    if item and len(item) > 0:
        return Error('邮箱已被注册', 400)

    line, last_id = MyFactory.createInstance('user.User', email=email, password=password).save()

    user = UserOrm.orm.find().where(id=last_id).first().end()

    return Response(user.to_json(), status=200)


@user_v.route('/update/', methods=['POST'])
def update():
    data = aj.load(request.get_data(as_text=True))
    email = data['email']
    password = data['password']
    try:
        item = UserOrm.orm.find().where(email=email, password=password).end()
        if not item or len(item) == 0:
            return Error('账号或密码错误', 400)
    except Exception as e:
        return Error(str(e))

    if "newPassword" in data.keys():
        data['password'] = data['newPassword']
        data.pop('newPassword')

    line = UserOrm.orm.update().set(**data).where(email=email, password=password).end()

    item = UserOrm.orm.find().where(email=email, password=data['password']).first().end()

    return Response(item.to_json(), status=200)
